﻿namespace org.webguvenligi.NSecureImageLib.GraphicFileFormats.PNG
{
    
    #region Imported Libraries
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
using System.IO;
    #endregion

    /// <summary>
    /// This Class Provides Defiltering Operations For Png
    /// Taken From Java Code in sixlegs png parser implementation
    /// </summary>
    public sealed class Defilterer
    {
     public Defilterer(Stream sourceStream, int bitDepth, 
                                            int samples, 
                                            int width)
     {

     }
    
    private static void Defilter(byte[] cur,
                                 byte[] prev,
                                 int bpp, 
                                 int filterType)
    {
        int rowSize = cur.Length;
        int xc, xp;
        switch (filterType) {
        case 0: // None
            break;
        case 1: // Sub
            for (xc = bpp, xp = 0; xc < rowSize; xc++, xp++)
                cur[xc] = (byte)(cur[xc] + cur[xp]);
            break;
        case 2: // Up
            for (xc = bpp; xc < rowSize; xc++)
                cur[xc] = (byte)(cur[xc] + prev[xc]);
            break;
        case 3: // Average
            for (xc = bpp, xp = 0; xc < rowSize; xc++, xp++)
                cur[xc] = (byte)(cur[xc] + ((0xFF & cur[xp]) + (0xFF & prev[xc])) / 2);
            break;
        case 4: // Paeth
            for (xc = bpp, xp = 0; xc < rowSize; xc++, xp++) {
                byte L = cur[xp];
                byte u = prev[xc];
                byte nw = prev[xp];
                int a = 0xFF & L; //  inline byte->int
                int b = 0xFF & u; 
                int c = 0xFF & nw; 
                int p = a + b - c;
                int pa = p - a; if (pa < 0) pa = -pa; // inline Math.abs
                int pb = p - b; if (pb < 0) pb = -pb; 
                int pc = p - c; if (pc < 0) pc = -pc;
                int result;
                if (pa <= pb && pa <= pc) {
                    result = a;
                } else if (pb <= pc) {
                    result = b;
                } else {
                    result = c;
                }
                cur[xc] = (byte)(cur[xc] + result);
            }
            break;
        default:
            throw new PNG.Exceptions.PNGBaseException("Unrecognized filter type " + filterType);
        }
      }
    }
}
